using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;

namespace ICSharpCode.AvalonEdit.Editing
{
    /// <summary>
    /// Margin showing line numbers.
    /// </summary>
    public class LineNumberMargin : AbstractMargin, IWeakEventListener
    {
        static LineNumberMargin()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof (LineNumberMargin),
                                                     new FrameworkPropertyMetadata(typeof (LineNumberMargin)));
        }

        private TextArea _textArea;

        private Typeface _typeface;
        private double _emSize;

        /// <inheritdoc/>
        protected override Size MeasureOverride(Size availableSize)
        {
            _typeface = this.CreateTypeface();
            _emSize = (double) GetValue(TextBlock.FontSizeProperty);
            var text = TextFormatterFactory.CreateFormattedText(
                this,
                new string('9', _maxLineNumberLength),
                _typeface,
                _emSize,
                (Brush) GetValue(Control.ForegroundProperty));
            return new Size(text.Width, 0);
        }

        /// <inheritdoc/>
        protected override void OnRender(DrawingContext drawingContext)
        {
            var textView = TextView;
            var renderSize = RenderSize;
            if (textView == null || !textView.VisualLinesValid) return;
            var foreground = _textArea.LineNumberForeground;
            foreach (var line in textView.VisualLines)
            {
                var lineNumber = line.FirstDocumentLine.LineNumber;
                var text = TextFormatterFactory.CreateFormattedText(
                    this,
                    lineNumber.ToString(CultureInfo.CurrentCulture),
                    _typeface, _emSize, foreground);
                drawingContext.DrawText(text, new Point(renderSize.Width - text.Width,
                                                        line.VisualTop - textView.VerticalOffset));
            }
        }

        /// <inheritdoc/>
        protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView)
        {
            if (oldTextView != null)
            {
                oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged;
            }
            base.OnTextViewChanged(oldTextView, newTextView);
            if (newTextView != null)
            {
                newTextView.VisualLinesChanged += TextViewVisualLinesChanged;

                // find the text area belonging to the new text view
                _textArea = newTextView.Services.GetService(typeof (TextArea)) as TextArea;
            }
            else
            {
                _textArea = null;
            }
            InvalidateVisual();
        }

        /// <inheritdoc/>
        protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument)
        {
            if (oldDocument != null)
            {
                TextDocumentWeakEventManager.LineCountChanged.RemoveListener(oldDocument, this);
            }
            base.OnDocumentChanged(oldDocument, newDocument);
            if (newDocument != null)
            {
                TextDocumentWeakEventManager.LineCountChanged.AddListener(newDocument, this);
            }
            OnDocumentLineCountChanged();
        }

        /// <inheritdoc cref="IWeakEventListener.ReceiveWeakEvent"/>
        protected virtual bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
        {
            if (managerType == typeof (TextDocumentWeakEventManager.LineCountChanged))
            {
                OnDocumentLineCountChanged();
                return true;
            }
            return false;
        }

        bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
        {
            return ReceiveWeakEvent(managerType, sender, e);
        }

        private int _maxLineNumberLength = 1;

        private void OnDocumentLineCountChanged()
        {
            int documentLineCount = Document != null ? Document.LineCount : 1;
            int newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length;

            // The margin looks too small when there is only one digit, so always reserve space for
            // at least two digits
            if (newLength < 2)
                newLength = 2;

            if (newLength != _maxLineNumberLength)
            {
                _maxLineNumberLength = newLength;
                InvalidateMeasure();
            }
        }

        private void TextViewVisualLinesChanged(object sender, EventArgs e)
        {
            InvalidateVisual();
        }

        private AnchorSegment _selectionStart;
        private bool _selecting;

        /// <inheritdoc/>
        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            if (!e.Handled && TextView != null && _textArea != null)
            {
                e.Handled = true;
                _textArea.Focus();

                SimpleSegment currentSeg = GetTextLineSegment(e);
                if (currentSeg == SimpleSegment.Invalid)
                    return;
                _textArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
                if (CaptureMouse())
                {
                    _selecting = true;
                    _selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length);
                    if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
                    {
                        var simpleSelection = _textArea.Selection as SimpleSelection;
                        if (simpleSelection != null)
                            _selectionStart = new AnchorSegment(Document, simpleSelection);
                    }
                    _textArea.Selection = new SimpleSelection(_selectionStart);
                    if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
                    {
                        ExtendSelection(currentSeg);
                    }
                }
            }
        }

        private SimpleSegment GetTextLineSegment(MouseEventArgs e)
        {
            var pos = e.GetPosition(TextView);
            pos.X = 0;
            pos.Y += TextView.VerticalOffset;
            var vl = TextView.GetVisualLineFromVisualTop(pos.Y);
            if (vl == null)
                return SimpleSegment.Invalid;
            var tl = vl.GetTextLineByVisualYPosition(pos.Y);
            int visualStartColumn = vl.GetTextLineVisualStartColumn(tl);
            int visualEndColumn = visualStartColumn + tl.Length;
            int relStart = vl.FirstDocumentLine.Offset;
            int startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart;
            int endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart;
            if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length)
                endOffset += vl.LastDocumentLine.DelimiterLength;
            return new SimpleSegment(startOffset, endOffset - startOffset);
        }

        private void ExtendSelection(SimpleSegment currentSeg)
        {
            if (currentSeg.Offset < _selectionStart.Offset)
            {
                _textArea.Caret.Offset = currentSeg.Offset;
                _textArea.Selection = new SimpleSelection(currentSeg.Offset,
                                                          _selectionStart.Offset + _selectionStart.Length);
            }
            else
            {
                _textArea.Caret.Offset = currentSeg.Offset + currentSeg.Length;
                _textArea.Selection = new SimpleSelection(_selectionStart.Offset, currentSeg.Offset + currentSeg.Length);
            }
        }

        /// <inheritdoc/>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (_selecting && _textArea != null && TextView != null)
            {
                e.Handled = true;
                SimpleSegment currentSeg = GetTextLineSegment(e);
                if (currentSeg == SimpleSegment.Invalid)
                    return;
                ExtendSelection(currentSeg);
            }
            base.OnMouseMove(e);
        }

        /// <inheritdoc/>
        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            if (_selecting)
            {
                _selecting = false;
                _selectionStart = null;
                ReleaseMouseCapture();
                e.Handled = true;
            }
            base.OnMouseLeftButtonUp(e);
        }

        /// <inheritdoc/>
        protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
        {
            // accept clicks even when clicking on the background
            return new PointHitTestResult(this, hitTestParameters.HitPoint);
        }
    }
}
